from fastapi import APIRouter, Request, Form
from ..common.schemas import IResponse, fail_resp, ok_resp
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from .service import ChatService
import json
from typing import List
from pydantic import BaseModel, Field

router = APIRouter(tags=["晓羊"])
templates = Jinja2Templates(directory="resource")

@router.get("/chat/demo2", response_class=HTMLResponse)
async def read_root(request: Request):
    return templates.TemplateResponse("demo.html", {"request": request, "question": ""})

class MemoTemplate(BaseModel):
    answer: str

@router.post("/chat/demo2")
async def answer(request: Request) -> IResponse[MemoTemplate]:
    # 获取原始的请求体（作为字节串）
    body_bytes = await request.body()
    # 将字节串解码为字符串
    body_str = body_bytes.decode('utf-8')
    # 将字符串解析为JSON对象（字典）
    body_json = json.loads(body_str)
    print(body_json.get('question'))
    # answer = "哈哈哈"
    answer = ChatService.chat_logic(body_json.get('question'))
    return ok_resp(data=MemoTemplate(answer=answer))


@router.get("/chat/demo", response_class=HTMLResponse)
async def read_root(request: Request):
    return templates.TemplateResponse("chat_demo.html", {"request": request, "question": ""})

@router.post("/chat/demo", response_class=HTMLResponse)
async def answer(request: Request, question: str = Form(...)):
    # answer = qa_database.get(question, "很抱歉，暂时无法为你提供该问题的答案，请更换问题试试。")
    answer = ChatService.chat_logic(question)
    return templates.TemplateResponse("chat_demo.html", {"request": request, "answer": answer, "question": question})

